# -*- coding:utf-8 -*-

from fastapi import APIRouter, Depends, HTTPException, Security, Request

from core.response import success_page, ResponsePage, ResponseModel, success
from core.dependencies import page_filter

from app.models.request.role import Role, RoleCreate, RoleUpdate, Permision, RolePersisionIn, RolePersision
from app.repository.role import RoleRepository
from app.service.user import check_login_user

from app.logger import getLogger

logger = getLogger()

router = APIRouter(prefix="/role")

@router.get("/", response_model=ResponsePage[Role], summary="角色列表查询", dependencies=[Security(check_login_user, scopes=["role_access"])])
async def role_pages(pageNo: int=1, pageSize: int=10
        , page_filter = Depends(page_filter)
        , repo: RoleRepository = Depends(RoleRepository)):
    data, total_page, total_rows = await repo.get_by_page(pageNo, pageSize, page_filter)
    return success_page(page_no=pageNo, page_size=pageSize, total_page = total_page, total_rows=total_rows, data=data)


@router.get("/{id}/info", response_model=ResponseModel[Role], summary="角色信息查询", dependencies=[Security(check_login_user, scopes=["role_access"])])
async def role_by_id(id: int, repo: RoleRepository = Depends(RoleRepository)):
    db_data = await repo.get_by_id(id)
    if db_data is None:
        raise HTTPException(status_code=404, detail="Role not found")
    return success(data=Role.from_orm(db_data))


@router.get("/info", response_model=ResponseModel[Role], summary="当前角色信息查询", dependencies=[Security(check_login_user, scopes=["role_access"])])
async def role_by_id(id: int, request: Request, repo: RoleRepository = Depends(RoleRepository)):
    db_data = await repo.get_by_id(request.state.user_id)
    if db_data is None:
        raise HTTPException(status_code=404, detail="Role not found")
    return success(data=Role.from_orm(db_data))


@router.post("/", response_model=ResponseModel[Role], summary="角色创建", dependencies=[Security(check_login_user, scopes=["role_create"])])
async def do_create_role(role: RoleCreate, request: Request, repo: RoleRepository = Depends(RoleRepository)):
    check_data = (await repo.get_filter(filter={"name": role.name})).first()
    if check_data is not None:
        raise HTTPException(status_code=400, detail="Role already exists")
    role = await repo.save(role, create_user=request.state.user_id)
    return success(data=Role.from_orm(role))

@router.delete("/{id}", response_model=ResponseModel[Role], summary="角色删除", dependencies=[Security(check_login_user, scopes=["role_delete"])])
async def do_delete_role(id: int, request: Request, repo: RoleRepository = Depends(RoleRepository)):
    check_data = await repo.get_by_id(id)
    if check_data is None:
        raise HTTPException(status_code=400, detail="Role not found")
    
    data = await repo.delete(id, delete_user=request.state.user_id)
    return success(data=data)

@router.put("/{id}", response_model=ResponseModel[Role], summary="角色信息修改", dependencies=[Security(check_login_user, scopes=["role_update"])])
async def do_update_role(id: int, data: RoleUpdate, request: Request, repo: RoleRepository = Depends(RoleRepository)):
    check_data = await repo.get_by_id(id)
    if check_data is None:
        raise HTTPException(status_code=400, detail=f"Role[{id}] not found")

    data = await repo.update(id, data, update_user=request.state.user_id)
    return success(data=Role.from_orm(data))

@router.get("/{id}/persiotions", response_model=ResponseModel[RolePersision], summary="角色权限查询", dependencies=[Security(check_login_user, scopes=["role_permision_access"])])
async def role_persisions_by_id(id: int, request: Request, repo: RoleRepository = Depends(RoleRepository)):
    check_data = await repo.get_by_id(id)
    if check_data is None:
        raise HTTPException(status_code=400, detail=f"Role[{id}] not found")
    check_data.permisions = (await repo.get_ref_by_ids([id], "tb_permision", "role_permision", Permision))[id]
    return success(data=RolePersision.from_orm(check_data))

@router.put("/{id}/persiotions", response_model=ResponseModel[RolePersision], summary="角色权限修改", dependencies=[Security(check_login_user, scopes=["role_permision_update"])])
async def do_update_role_persition(id: int, data: RolePersisionIn, request: Request, repo: RoleRepository = Depends(RoleRepository)):
    check_data = await repo.get_by_id(id)
    if check_data is None:
        raise HTTPException(status_code=400, detail=f"Role[{id}] not found")
    if data.permisions is not None:
        permision_ids = [permision.id for permision in (await repo.get_ref_by_ids([id], "tb_permision", "role_permision", Permision))[id]]
        logger.info(f"permisions: {data.permisions}, permision_ids: {permision_ids}")
        
        delete_permision_ids = [id for id in permision_ids if int(id) not in data.permisions]
        logger.info(f"delete_permision_ids: {delete_permision_ids}")
        await repo.delete_ref(id, delete_permision_ids, "tb_permision", "role_permision", delete_user=request.state.user_id)
        # 验证新增的权限是否合法
        add_permision_ids = [id for id in data.permisions if str(id) not in permision_ids]
        logger.info(f"add_permision_ids: {add_permision_ids}")
        await repo.add_ref(id, add_permision_ids, "tb_permision", "role_permision", request.state.user_id)

    check_data.permisions = (await repo.get_ref_by_ids([id], "tb_permision", "role_permision", Permision))[id]
    return success(data=RolePersision.from_orm(check_data))
